/******************************************************************************
 *	@Author Raffaello Brondi
 *
 * 	@description Javascript Object representing a FB user.
 *
 ******************************************************************************/


/**
 * An object that rapresents a FB user.
 */
function User() {
	this.userId = undefined;
	this.name = undefined;
	this.token = undefined;
	this.logged = false;
	this.listeners = {};
}

User.prototype = {
	constructor : User,

	/**************************************************************************
	 *						GETTERS & SETTERS 
	 *************************************************************************/
	isLogged : function(){
		return this.logged;
	},

	getAccessToken : function(){
		return this.token;
	},

	getUserId : function(){
		return this.userId;
	},

	getName : function(){
		return this.name;
	},

	setUserId : function(id){
		this.userId = id;
	},

	setAccessToken : function(tok){
		this.token = tok;
	},

	setLogged : function(val){
		this.logged = val;
	},


	/**************************************************************************
	 *								EVENTS
	 *************************************************************************/

	addListener: function(event, listener){
		if (typeof this.listeners[event] == "undefined"){
			this.listeners[event] = new Array();
		}

		this.listeners[event].push(listener);
	},

	fire: function(event){
		log('FBUser: firing event: ' + event);
		if (typeof event == "string"){
			event = { "type": event };
		}
		if (!event.target){
			event.target = this;
		}

		if (!event.type){ 
			throw new Error("Event object missing 'type' property.");
		}

		if (this.listeners[event.type] instanceof Array){
			var listeners = this.listeners[event.type];
			for (var i = 0, len = listeners.length; i < len; i++){
				listeners[i].call(this, event);
			}
		}
	},

	removeListener: function(event, listener){
		if (this.listeners[event] instanceof Array){
			var eListeners = this.listeners[event];
			for (var i=0, len=eListeners.length; i < len; i++){
				if (eListeners[i] === listener){
					eListeners.splice(i, 1);
					break;
				}
			}
		}
	},

	/**************************************************************************
	 *							METHODS
	 *************************************************************************/

	serialize : function(){
		return JSON.stringify(this, null, 2);
	},

	saveProfile : function() {
		var req = new Request();
		this.addListener('onLogout', req.abort.bind(req));
		req.setOnSuccess(function(response){
			this.removeListener('onLogout', req.abort);
			if(!response.alreadyRegistered)
				this.dumpProfile();
			else{
				this.name = response.user.name;
				this.fire('onProfileAcquired');
			}
			this.updateAccessToken();
		}.bind(this));

		req.setOnFailure(function(response){
			this.removeListener('onLogout', req.abort);
			var error = new Object();
			error.message = 'Non è stato possibile verificare la presenza dell\'utente nel db ';
			error.location = 'saveProfile[user.js]';
			error.id = this.id;
			error.level = 0;
			this.logError(error);
		}.bind(this));

		req.asyncGetRequest(getRestUrl() + 'user/' + this.userId);
	},

	updateAccessToken : function() {
		var req = new Request();
		req.setOnSuccess(function(response){
			//TODO altro da fare?
			return;
		});

		req.setOnFailure(function(response){
			var error = new Object();
			error.message = 'Non è stato possibile aggiornare l\'access token';
			error.location = 'updateAccessToken[user.js]';
			error.id = this.id;
			error.level = 0;
			this.logError(error);
		}.bind(this));

		req.asyncPutRequest(getRestUrl() + 'user/'+ this.userId + '/token/' + this.token);
	},
	dumpProfile : function(){
		log('First time for ' + this.userId);

		FB.api('/me', function(response){
			log('Dump user profile ' + response.id);
			this.name = response.name;
			this.fire('onProfileAcquired');
			var req = new Request();

			req.setOnSuccess(function(){
				//TODO altro da fare?
				return;
			}.bind(this));

			response.drupal_user = Drupal.settings.sonna_login.drupal_user;

			req.setOnFailure(function(response){
				var error = new Object();
				error.message = 'Non è stato possibile salvare il profilo utente sul db ';
				error.location = 'saveProfile[user.js]';
				error.id = this.id;
				error.level = 0;
				this.logError(error);
			}.bind(this));

			req.asyncPostRequest(getRestUrl() + 'user', JSON.stringify(response));
		}.bind(this));

	},

	logError : function(param){
		var reqError = new Request();
		reqError.asyncPostRequest(getRestUrl() + 'error', param);
	},

	login: function(authResponse){
		this.userId = authResponse.userID;
		this.token = authResponse.accessToken;
		this.logged = true;
		this.fire('onLogin');
		this.saveProfile();
	},

	logout: function(){
		this.userId = undefined;
		this.token = undefined;
		this.logged = false;
		this.fire('onLogout');
	},

	like : function(params) {
		log(params);
		alert('like!')
	},

	unlike : function(params) {
		log(params);
		alert('unlike!');
	}
}
